package cn.edu.sdjzu.xg.eagle.Service;

import cn.edu.sdjzu.xg.eagle.dao.OrganizationDao;
import cn.edu.sdjzu.xg.eagle.entity.Organization;
import cn.edu.sdjzu.xg.eagle.util.JdbcPoolUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

public class OrganizationService implements OrganizationServiceInterface{

    private static final OrganizationServiceInterface instance = new OrganizationService();

    private OrganizationDaoInterface organizationDao = new OrganizationDao();

    private OrganizationService(){}

    public static OrganizationServiceInterface getInstance(){ return instance; }

    @Override
    public void save(Organization organization) {
        try (Connection conn = JdbcPoolUtil.getConn()) {
            organizationDao.save(conn, organization);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(Organization organization) {
        try (Connection conn = JdbcPoolUtil.getConn()) {
            organizationDao.update(conn, organization);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(Long id) {
        try (Connection conn = JdbcPoolUtil.getConn()) {
            organizationDao.delete(conn, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Organization findById(Long id) {
        Organization organization = null;
        try (Connection conn = JdbcPoolUtil.getConn()) {
            organization = organizationDao.findById(conn, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return organization;
    }

    @Override
    public Collection<Organization> findAll() {
        Collection<Organization> organizations = new ArrayList<>();
        try (Connection conn = JdbcPoolUtil.getConn()) {
            organizations = organizationDao.findAll(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return organizations;
    }

    @Override
    public Collection<Organization> findAllChildren(Long parentId) {
        Collection<Organization> organizations = new ArrayList<>();
        try (Connection conn = JdbcPoolUtil.getConn()) {
            organizations = organizationDao.findAllChildren(conn, parentId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return organizations;
    }
}
